const express = require('express');
const Mock = require('mockjs');
const app = express();
// 跨域处理
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", 'Express');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
let id = 1;

function getNewsData(num) {
    return Mock.mock({
        [`list|${num}`]: [{
            // 模拟id，从1开始自增
            'id|+1': id,
            // 模拟新闻标题，中文字符串长度为15~25
            title: "@ctitle(15, 25)",
            // 模拟新闻来源，中文字符串长度为3~5
            from: "@ctitle(3, 5)",
            // 模拟新闻发布时间
            time: "@natural(1, 24)" + "小时前",
            // 模拟新闻图片索引，自然数0~4
            imgIdx: "@natural(0, 4)"
        }]
    })
}

app.get('/news', (req, res) => {
    const num = req.query.num;
    if (num) {
        res.send(getNewsData(num))
        id += parseInt(num);
        console.log(id)
    } else {
        res.status(400).send("参数错误");
    }
})
app.listen(4000, () => {
    console.log('server starts at localhost:4000...');
})